package GlavFinans::Module::Customer::Controller::Join;

use utf8;
use Data::Dumper;
use Mojo::Base 'Mojolicious::Controller';

use Crypt::GeneratePassword qw(word); 

sub index {
	my $self = shift;
	$self->render('core/join/index');
}

sub create {
	my $self = shift;
	
	my $form = $self->req->params->to_hash;
		
	# Validation Rule
	my $rule = [
		'email' => {
			message => 'Указан неверный e-mail адрес'
		} => ['not_blank || email'],
		'phone' => {
			message => 'Указан неверный номер телефона'
		} => ['not_blank || phone'],
		'accept' => {
			message => 'Для регистрации необходимо согласиться с правилами сайта'
		} => ['not_blank']
	];
	
	my $vc = $self->stash('validator');	
	my $result = $vc->validate($form, $rule);
	$form = $result->data;
	
	if ($result->is_ok) {
		# Get valid data
		# TODO: create user with role customer
		
		my $role = $self->app->db->resultset('Role')->search( {name => 'customer'} )->single;
		my $customer = $self->app->db->resultset('Customer')->new();
		$customer->password( word(12, 12) );
		$customer->email($form->{email});
		$customer->phone($form->{phone});
		$customer->role($role);
		$customer->insert();
		
		my $message = $self->app->render_mail('core/join/join', customer => $customer);
		$self->app->mail(
			to      => $customer->email(),
			subject => 'Регистрация на сайте GlavFinans.ru',
			data    => $message
		);
		$self->flash(success => 1);
		$self->redirect_to('/join/success');   
	} else {
		$self->stash(missing => 1) if $result->has_missing;
		$self->stash(messages => $result->messages_to_hash) if $result->has_invalid;
		$self->stash(form => $form);
		$self->render('core/join/index');
	}
	
	
}
1;
